<template>
  <div class="detailMain" id="ttt">
    <a-row>
      <a-col :lg="10" :xl="8" :xxl="6">
        <div class="top-btns">
          <a-button type="primary" @click="confirmHint('', 'save')">保存</a-button>
          <a-button type="primary" @click="backConfirm">返回</a-button>
        </div>
      </a-col>
    </a-row>
    <a-form :form="form">
      <a-collapse class="form-wrap basic-form" v-model="activeKey">
        <a-collapse-panel header="基础信息" key="0">
          <a-form-item label="商家分类：">
            <a-cascader
              v-model="createIndustry"
              :fieldNames="fieldNames"
              :options="industryObj"
              @change="onChangeCategory"
              placeholder="请选择商家分类"
            />
          </a-form-item>
          <a-form-item label="门店定位：">
            <a-input v-model="params.location" @click="selectAddress" placeholder="请选择门店定位地址">
              <a-icon type="solution" />
            </a-input>
          </a-form-item>
          <a-modal title="门店定位" v-model="visible" @ok="handleMapOk" class="map-modal">
            <div class="map-scroll">
              <label class="map-keywords">
                门店定位：
                <a-input v-model="keyword" />
              </label>
              <baidu-map>
                <bm-view class="map"></bm-view>
                <bm-local-search
                  :keyword="keyword"
                  :auto-viewport="true"
                  @infohtmlset="infohtmlset"
                  :location="location"
                ></bm-local-search>
              </baidu-map>
            </div>
          </a-modal>
          <a-form-item label="所属区域">
            <area-select @handlePlace="selectArea" :createPlace="params.basic_area" />
          </a-form-item>
          <a-form-item label="详细地址：">
            <a-input v-model.trim="params.address_detail" placeholder="请输入详细的地址" />
          </a-form-item>
        </a-collapse-panel>
        <a-collapse-panel header="*推荐人信息" key="1">
          <a-form-item label="*推荐人姓名：">
            <a-input
              v-model.trim="params.partner_name"
              :disabled="nameDisabled"
              @click="openSPShow()"
              placeholder="请选择推荐人"
            />
          </a-form-item>
          <a-form-item label="*推荐人手机号：">
            <a-input v-model.trim="params.partner_phone" disabled />
          </a-form-item>
        </a-collapse-panel>
        <a-collapse-panel key="2">
          <template slot="header">
            <div>
              门头信息(商家简称需要与门头照片一致)
              <a>示例图</a>
            </div>
          </template>
          <a-form-item label="商家简称：">
            <a-input v-model.trim="params.merchant_name" placeholder="请输入商家简称" />
          </a-form-item>
          <!-- head_img -->
          <a-form-item label="门头照片：">
            <a-upload
              name="avatar"
              listType="picture-card"
              class="avatar-uploader"
              :showUploadList="false"
              :customRequest="handleChangeHeadImg"
            >
              <img class="min-pic" v-if="params.head_img" :src="params.head_img" alt />
              <div v-else>
                <a-icon :type="loading ? 'loading' : 'plus'" />
                <div class="ant-upload-text">上传图片</div>
              </div>
            </a-upload>
          </a-form-item>
        </a-collapse-panel>
        <a-collapse-panel header="营业信息" key="3">
          <a-form-item label="营业时间：">
            <a-time-picker
              v-if="params.business_start"
              :defaultValue="moment(params.business_start, 'HH:mm')"
              format="HH:mm"
              class="business-time"
              placeholder="营业开始时间"
              @change="changeBeginTime"
            />
            <a-time-picker
              v-if="params.business_end"
              :defaultValue="moment(params.business_end, 'HH:mm')"
              format="HH:mm"
              class="business-time"
              placeholder="营业结束时间"
              @change="changeEndTime"
            />
          </a-form-item>
          <a-form-item label="人均消费：" class="number-style">
            <a-input-number
              :min="0"
              :step="5"
              :precision="1"
              v-model.trim="params.per_consume"
              placeholder="请输入人均消费"
            />
          </a-form-item>
          <a-form-item
            label="客服电话："
            :validate-status="valid1.status"
            :help="valid1.txt"
          >
            <a-input
              v-model.trim="params.service_phone"
              placeholder="请输入客服电话"
              @change="handleSerPhone"
            />
          </a-form-item>
          <a-form-item label="发行额度：" class="number-style">
            <a-input-number
              :min="0"
              :step="5"
              :precision="1"
              v-model.trim="params.amount"
              placeholder="请输入发行额度"
            />
          </a-form-item>
          <a-form-item label="折扣：" class="number-style">
            <a-input-number
              :min="0"
              :max="10"
              :step="0.5"
              :precision="1"
              v-model.trim="params.discount"
              placeholder="请输入折扣(0-10)"
            />
          </a-form-item>
        </a-collapse-panel>
        <a-collapse-panel header="店内照片(需要干净整洁的店内照片,最少5张,最多12张)" key="4">
          <a-button
            class="add-newpic"
            type="primary"
            @click="addstore()"
            v-if="storeImgs.length < 12"
          >添加图片和标签</a-button>
          <a-form-item label>
            <div
              class="upload-item"
              v-for="(item, index) in storeImgs"
              :key="index"
              @click="getIndex(index)"
            >
              <a-upload
                name="avatar"
                listType="picture-card"
                class
                :showUploadList="false"
                :multiple="true"
                :customRequest="handleChange"
              >
                <img class="min-pic" v-if="item.url" :src="item.url" alt />
                <div v-else>
                  <a-icon :type="loading ? 'loading' : 'plus'" />
                  <div class="ant-upload-text">上传图片</div>
                </div>
              </a-upload>
              <a-form-item label="标签：" class="pic-tag">
                <a-select placeholder="请选择标签" v-model="item.tag_id" :disabled="item.url?false:true">
                  <a-select-option
                    v-for="TagItem in storeTag"
                    :value="TagItem.id"
                    :key="TagItem.id"
                  >{{TagItem.name}}</a-select-option>
                </a-select>
              </a-form-item>
              <a-button
                style="float: right;margin-top: 4px;"
                @click="deleteImg('storeImgs',index)"
              >删除</a-button>
              <!-- <div v-if="storeImgs.length < 12">
                <a-icon type="plus"/>
                <div class="ant-upload-text">上传图片</div>
              </div>-->
            </div>
          </a-form-item>
        </a-collapse-panel>
        <a-collapse-panel header="产品照片(需要清晰且完整的产品照片,最少5张,最多12张)" key="5">
          <a-form-item>
            <!-- priceImg -->
            <a-button
              class="add-newpic"
              type="primary"
              @click="addProduct()"
              v-if="productPics.length < 12"
            >添加图片和标签</a-button>
            <a-form-item label>
              <div
                class="upload-item"
                v-for="(item,index) in productPics"
                :key="index"
                @click="getIndex(index)"
              >
                <a-upload
                  name="avatar"
                  listType="picture-card"
                  class
                  :showUploadList="false"
                  :customRequest="handleProductChange"
                >
                  <img class="min-pic" v-if="item.url" :src="item.url" alt />
                  <div v-else>
                    <a-icon type="plus" />
                    <div class="ant-upload-text">上传图片</div>
                  </div>
                </a-upload>
                <a-form-item label="标签：" class="pic-tag">
                  <a-input v-model.trim="item.name" placeholder="请输入产品名称（12个字以内）" maxlength="12" />
                </a-form-item>
                <a-form-item label="价格：" class="pic-tag">
                  <a-input type="number" v-model.trim="item.price" placeholder="请输入产品价格" />
                </a-form-item>
                <a-button style="float: right;margin-top: 4px;" @click="deleteProductPic(index)">删除</a-button>
              </div>
            </a-form-item>
          </a-form-item>
        </a-collapse-panel>
        <a-collapse-panel header="价格表照片(需要清晰且完整的价格表照片,最少1张,最多12张)" key="6">
          <a-form-item>
            <!-- priceImg -->
            <a-button
              class="add-newpic"
              type="primary"
              @click="addPrice()"
              v-if="priceImg.length < 12"
            >添加图片和标签</a-button>
            <a-form-item label>
              <div
                class="upload-item"
                v-for="(item,index) in priceImg"
                :key="index"
                @click="getIndex(index)"
              >
                <a-upload
                  name="avatar"
                  listType="picture-card"
                  class
                  :showUploadList="false"
                  :customRequest="handlePriceChange"
                >
                  <img class="min-pic" v-if="item.url" :src="item.url" alt />
                  <div v-else>
                    <a-icon :type="loading ? 'loading' : 'plus'" />
                    <div class="ant-upload-text">上传图片</div>
                  </div>
                </a-upload>
                <a-form-item label="标签：" class="pic-tag">
                  <a-select
                    placeholder="请选择标签"
                    v-model="item.tag_id"
                    :disabled="item.url?false:true"
                  >
                    <a-select-option
                      v-for="(TagItem) in priceTag"
                      :value="TagItem.id"
                      :key="TagItem.id"
                    >{{TagItem.name}}</a-select-option>
                  </a-select>
                </a-form-item>
                <a-button
                  style="float: right;margin-top: 4px;"
                  @click="deleteImg('priceImg',index)"
                >删除</a-button>
                <!-- <div v-if="storeImgs.length < 12">
                <a-icon type="plus"/>
                <div class="ant-upload-text">上传图片</div>
                </div>-->
              </div>
            </a-form-item>
          </a-form-item>
        </a-collapse-panel>
        <a-collapse-panel header="法人信息" key="7">
          <a-form-item label="法人姓名：">
            <a-input v-model.trim="params.law_name" placeholder="请输入法人姓名" />
          </a-form-item>
          <a-form-item
            label="身份证："
            :validate-status="valid2.status"
            :help="valid2.txt"
          >
            <a-input
              v-model.trim="params.law_idno"
              placeholder="请输入身份证号"
              @change="handleIdno"
            />
          </a-form-item>
        </a-collapse-panel>
        <a-collapse-panel header="营业执照信息(执照文字需清晰可见且完整,且与名称类型保持一致)" key="8">
          <a-form-item label="执照名称：">
            <a-input v-model.trim="params.store_name" placeholder="请输入执照名称" />
          </a-form-item>
          <!-- merchantImg -->
          <a-form-item label="营业执照：">
            <a-upload
              name="avatar"
              listType="picture-card"
              class="avatar-uploader"
              :showUploadList="false"
              :customRequest="handleChangeLicenseImg"
            >
              <img class="min-pic" v-if="params.license" :src="params.license" alt />
              <div v-else>
                <a-icon type="plus" />
                <div class="ant-upload-text">上传图片</div>
              </div>
            </a-upload>
          </a-form-item>
        </a-collapse-panel>
        <a-collapse-panel header="经营许可证(选填,许可证文字需清晰可见且完整)" key="9">
          <a-form-item label="经营许可证">
            <a-upload
              name="avatar"
              listType="picture-card"
              class="avatar-uploader"
              :showUploadList="false"
              :customRequest="handleChangeLicensePermitImg"
            >
              <img class="min-pic" v-if="params.license_premit" :src="params.license_premit" alt />
              <div v-else>
                <a-icon type="plus" />
                <div class="ant-upload-text">上传图片</div>
              </div>
            </a-upload>
          </a-form-item>
        </a-collapse-panel>
        <a-collapse-panel header="结算信息" key="10">
          <a-form-item label="账户类型：">
            <a-select v-model="params.bank_type" placeholder="请选择账户类型">
              <a-select-option :value="1">对公账户</a-select-option>
              <a-select-option :value="2">法人账户</a-select-option>
            </a-select>
          </a-form-item>
          <a-form-item label="开户银行：">
            <!-- v-model="params.bankname" -->
            <a-select placeholder="请选择开户银行" v-model="params.bankname" @change="handleBankChange">
              <a-select-option v-for="item in banknames" :key="item.id" :value="item.id">
                <img class="bank-icon" v-if="item.icon_s" :src="item.icon_s" alt />
                {{item.bankname}}
              </a-select-option>
            </a-select>
          </a-form-item>
          <a-form-item
            label="银行账号："
            :validate-status="valid3.status"
            :help="valid3.txt"
          >
            <a-input
              v-model.trim="params.bankcard"
              placeholder="请输入银行账号"
              @change="handleBankcard"
            />
          </a-form-item>
          <a-form-item label="开户银行支行：">
            <a-input v-model.trim="params.branchname" placeholder="请输入开户银行支行" />
          </a-form-item>
          <!-- 开户地区 -->
          <a-form-item label="开户地区">
            <area-select
              :tiptxt="tiptxt"
              @handlePlace="selectBranchArea"
              :createPlace="params.branch_area"
              placeholder="请选择开户地区"
            />
          </a-form-item>
          <a-form-item label="会员账号">
            <a-input
              @click="openMenber()"
              :disabled="menberDisabled"
              v-model="params.member_account"
              placeholder="请选择会员账号"
            />
          </a-form-item>
        </a-collapse-panel>
        <a-collapse-panel header="注册信息" key="11">
          <a-form-item
            label="手机号码："
            :validate-status="valid4.status"
            :help="valid4.txt"
          >
            <a-input
              v-model.trim="params.phone"
              placeholder="请输入手机号码"
              @change="handlePhone"
            />
          </a-form-item>
        </a-collapse-panel>
        <!-- <a-collapse-panel header="注册信息" key="12">
          <a-form-item label="商户结算费率：">
            <a-input v-model="params.settleRate" placeholder="请输入商户结算费率"/>
          </a-form-item>
          <a-form-item label="产品交易手续费：">
            <a-input v-model="params.tradeRate" placeholder="请输入产品交易手续费"/>
          </a-form-item>
        </a-collapse-panel>-->
      </a-collapse>
    </a-form>
    <div class="modal-wrap">
      <!-- 保存确认框 -->
      <confirm-modal :hint="hint" @handleConfirm="handleConfirmOk" ref="openModal" />
      <!-- 选择会员 -->
      <a-modal
        v-model="menberShow"
        class="wide-modal"
        title="选择会员"
        @ok="ChoiceMenber()"
        @cancel="cancelMenber"
      >
        <a-row>
          <a-col :lg="14" :xl="8" :xxl="12">
            <a-input v-model.trim="memberName" placeholder="请输入会员账号、名称或联系方式"></a-input>
          </a-col>
          <a-col :lg="6" :xl="8" :xxl="4" class="search">
            <a-button type="primary" @click="getMember()">查询</a-button>
          </a-col>
          <a-table
            :columns="menberList"
            :rowKey="record => record.account"
            :dataSource="menberData"
            :loading="menberLoading"
            :pagination="false"
            :rowSelection="rowSelection"
          >
            <template slot="name" slot-scope="name">{{name.first}} {{name.last}}</template>
          </a-table>
        </a-row>
      </a-modal>
      <!-- 选择服务商 -->
      <a-modal v-model="SPShow" class="wide-modal" title="选择服务商" @ok="ChoiceSP()" @cancel="cancelSP">
        <a-row>
          <a-col :lg="14" :xl="8" :xxl="12">
            <a-input v-model.trim="SPName" placeholder="请输入服务商账号、名称或联系方式"></a-input>
          </a-col>
          <a-col :lg="6" :xl="8" :xxl="4" class="search">
            <a-button type="primary" @click="getMember()">查询</a-button>
          </a-col>
          <a-table
            :columns="SPList"
            :rowKey="record => record.account"
            :dataSource="SPData"
            :loading="SPLoading"
            :pagination="false"
            :rowSelection="rowSelection"
          >
            <template slot="name" slot-scope="name">{{name.first}} {{name.last}}</template>
          </a-table>
        </a-row>
      </a-modal>
      <a-modal
        v-model="backVisible"
        title="返回确认"
        :footer="null"
        class="back-pop"
      >
        <p>页面未保存，是否离开该页面！</p>
        <div class="back-btn-wrap">
          <a-button
            type="primary"
            @click="closePop"
          >取消</a-button>
          <a-button
            type="primary"
            @click="handleConfirmOk"
          >离开并保存</a-button>
          <a-button
            type="primary"
            @click="backDeatil"
          >离开</a-button>
        </div>
      </a-modal>
    </div>
    <back-top />
  </div>
</template>

<script>
import {
  inviteShowDetail,
  getCategoryTag,
  uploadImg,
  deleteImage,
  getMember,
  getPartner,
  getPictureTag,
  inviteUpdate
} from '../../store/providerApi.js'
import { sysbank } from '../../store/action'
import { isPhone, Landline, CheckCardNo, isCardNum } from '../../utils/check'
import moment from 'moment'
let temporaryData = null
const rowSelection = {
  type: 'radio',
  onChange(selectedRowKeys, selectedRows) {
    temporaryData = { ...selectedRows[0] }
  }
}
// 压缩图片
export function resizeImage(file) {
    return new Promise((resolve, reject) => {
        var reader = new FileReader()
        reader.onload = () => {
            var img = new Image()
            img.onload = () => {
                var w = img.naturalWidth
                var h = img.naturalHeight
                var maxW = 600
                var maxH = 424
                // 如果图片尺寸小于最大限制，则不压缩直接上传
                if (w <= maxW && h <= maxH) {
                    resolve(file)
                    return
                }
                var level = 0.6
                var multiple = Math.max(w / maxW, h / maxH)
                var resizeW = w / multiple
                var resizeH = h / multiple
                var canvas = document.createElement('canvas')
                canvas.width = resizeW
                canvas.height = resizeH
                var ctx = canvas.getContext('2d')
                ctx.drawImage(img, 0, 0, resizeW, resizeH)
                var base64Img = canvas.toDataURL(file.type, level)
                var arr = base64Img.split(',')
                resolve(arr[1])
            }

            img.src = reader.result
        }
        reader.readAsDataURL(file)
    })
}
// 数据blod对象
export function convertToBlob(base64Str, fileType) {
    var base64 = window.atob(base64Str)
    var len = base64.length
    var buff = new ArrayBuffer(len)
    var uarr = new Uint8Array(buff)

    for (var i = 0; i < len; i++) {
        uarr[i] = base64.charCodeAt(i)
    }

    var blob = null

    try {
        blob = new Blob([buff], { type: fileType })
    } catch (e) {
        var BlobBuilder = (window.BlobBuilder =
            window.BlobBuilder ||
            window.WebKitBlobBuilder ||
            window.MozBlobBuilder ||
            window.MSBlobBuilder)

        if (e.name === 'TypeError' && BlobBuilder) {
            var builder = new BlobBuilder()
            builder.append(buff)
            blob = builder.getBlob(fileType)
        }
    }
    return blob
};
let paramsData
let sendData
let sends
export default {
  data() {
    return {
      valid1: {
        status: 'success',
        txt: ''
      },
      valid2: {
        status: 'success',
        txt: ''
      },
      valid3: {
        status: 'success',
        txt: ''
      },
      valid4: {
        status: 'success',
        txt: ''
      },
      loading: false,
      menberShow: false,
      SPShow: false,
      menberList: [
        {
          title: '会员id',
          dataIndex: 'id'
        },
        {
          title: '会员账号',
          dataIndex: 'account'
        },
        {
          title: '手机号码',
          dataIndex: 'phone'
        }
      ],
      SPList: [
        {
          title: 'id',
          dataIndex: 'id'
        },
        {
          title: '服务商账号',
          dataIndex: 'account'
        },
        {
          title: '服务商名称',
          dataIndex: 'name'
        },
        {
          title: '手机号码',
          dataIndex: 'phone'
        },
        {
          title: '所在区域',
          dataIndex: 'address'
        }
      ],
      nameDisabled: false,
      menberDisabled: false,
      SPLoading: false,
      SPData: [],
      SPName: '',
      memberName: '',
      menberData: [],
      temporaryData,
      rowSelection,
      menberLoading: false,
      menberSP: false,
      visible: false,
      backVisible: false,
      location: '深圳',
      keyword: '深圳',
      fieldNames: { label: 'name', value: 'id', children: 'second' },
      detailData: {},
      imgIndex: '',
      options: [],
      createIndustry: [],
      storeImgs: [],
      formLayout: 'horizontal',
      form: this.$form.createForm(this),
      loading: false,
      activeKey: ['0', '1', '2', '3', '4', '5', '6', '7', '8', '9', '10', '11'],
      hint: '',
      tiptxt: '请选择开户地区',
      suffixIcon: '',
      industryObj: [],
      // v-model变量
      params: {
        id: '',
        tag_id: '',
        location: '', // 门店定位
        lon: '', // 经度
        lat: '', // 纬度
        basic_area: null, // 所属位置
        province_id: '',
        city_id: '',
        district_id: '',
        address_detail: '', // 详细地址
        branch_area: null, // 开户地区
        bank_province_id: '',
        bank_city_id: '',
        bank_district_id: '',
        partner_name: '', // 推荐人姓名
        partner_phone: '', // 推荐人手机号
        pa_id: '',
        store_name: '', // 商家简称
        business_start: '', // 营业开始时间
        business_end: '', // 营业结束时间
        per_consume: '', // 人均消费
        service_phone: '', // 客服电话
        amount: '', // 发行额度
        discount: '', // 折扣
        law_name: '', // 法人姓名
        law_idno: '', // 法人身份证
        merchant_name: '', // 执照名称
        license: '',
        license_premit: '',
        bank_type: '', // 账户类型
        bank_id: '',
        bankname: 0, // 开户银行
        bankcard: '', // 银行账号
        branchname: '', // 开户银行支行
        member_account: '', // 会员账号
        member_id: '',
        phone: '', // 注册信息手机号码
        settleRate: '', // 结算费率
        tradeRate: '', // 产品交易手续费
        head_img: ''
      },
      // 上传图片
      previewVisible: false,
      previewImage: '',
      fileList: [],
      productPics: [],
      storeTag: [],
      priceImg: [],
      priceTag: [],
      banknames: []
    }
  },
  mounted() {
    this.getData()
  },
  methods: {
    moment,
    // 打开会员弹窗
    openMenber() {
      this.menberShow = true
      this.menberDisabled = true
      this.getMember()
    },
    // 打开服务商弹窗
    openSPShow() {
      this.SPShow = true
      this.nameDisabled = true
      this.getPartner()
    },
    getIndex(index) {
      this.imgIndex = index
    },
    onChangeCategory(value) {
      this.params.tag_id = value[1]
    },
    handleBankChange(val) {
      this.params.bank_id = val
    },
    setDefultCategory(item) {
      if (item.category_id && item.tag_id) {
        this.createIndustry = [item.category_id, item.tag_id]
      }
    },
    // 获取页面数据
    getData() {
      // 商家分类
      getCategoryTag().then(res => {
        this.industryObj = res.data
      })
      // 系统银行
      sysbank().then(res => {
        this.banknames = res.data
      })
      // 详情数据
      inviteShowDetail({
        id: this.$route.query.id
      }).then(res => {
        let datas = res.data
        this.detailData = datas
        this.setDefultCategory(datas)
        console.log(datas)
        this.params = {
          id: this.$route.query.id,
          tag_id: datas.tag_id,
          basic_area: [datas.province_id, datas.city_id, datas.district_id], // 所属位置
          province_id: datas.province_id,
          city_id: datas.city_id,
          district_id: datas.district_id,
          location: datas.location, // 门店定位
          lon: datas.lon, // 经度
          lat: datas.lat, // 纬度
          address_detail: datas.address_detail, // 详细地址
          branch_area: [
            datas.bank_province_id,
            datas.bank_city_id,
            datas.bank_district_id
          ], // 开户地区
          bank_province_id: datas.bank_province_id,
          bank_city_id: datas.bank_city_id,
          bank_district_id: datas.bank_district_id,
          partner_name: datas.partner_name, // 推荐人姓名
          partner_phone: datas.partner_phone, // 推荐人手机号
          pa_id: datas.pa_id,
          store_name: datas.store_name, // 执照名称
          per_consume: datas.per_consume, // 人均消费
          service_phone: datas.service_phone, // 客服电话
          amount: datas.amount, // 发行额度
          discount: datas.discount, // 折扣
          law_name: datas.law_name, // 法人姓名
          law_idno: datas.law_idno, // 法人身份证
          merchant_name: datas.merchant_name, // 商家简称
          bank_type: datas.bank_type === 0 ? '' : datas.bank_type, // 账户类型
          bank_id: datas.bank_id,
          bankname: datas.bankname, // 开户银行
          bankcard: datas.bankcard, // 银行账号
          branchname: datas.branchname, // 开户银行支行
          member_account: datas.member_account, // 会员账号
          member_id: datas.member_id,
          phone: datas.phone, // 注册信息手机号码
          business_start: datas.business_start || '00:00', // 营业开始时间
          business_end: datas.business_end || '00:00', // 营业结束时间
          head_img: datas.head_img,
          license: datas.license,
          license_premit: datas.license_premit,
          store_pics: this.storeImgs,
          price_pics: this.priceImg,
          product_pics: this.productPics
        }
        this.keyword = this.params.location || '深圳'
        for (let i = 0; i < datas.store_pics.length; i++) {
          this.storeImgs.push({
            id: datas.store_pics[i].id,
            name: datas.store_pics[i].name,
            url: datas.store_pics[i].cover_org, // 需
            tag_id: datas.store_pics[i].tag_id || '', // 需
            price: datas.store_pics[i].price,
            tag_name: datas.store_pics[i].tag_name
          })
        }
        for (let i = 0; i < datas.product_pics.length; i++) {
          this.productPics.push({
            id: datas.product_pics[i].id,
            name: datas.product_pics[i].name || '', // 需
            url: datas.product_pics[i].cover_org,
            tag_id: datas.product_pics[i].tag_id,
            price: datas.product_pics[i].price || '', // 需
            tag_name: datas.product_pics[i].tag_name
          })
        }
        for (let i = 0; i < datas.price_pics.length; i++) {
          this.priceImg.push({
            id: datas.price_pics[i].id,
            name: datas.price_pics[i].name,
            url: datas.price_pics[i].cover_org, // 需
            tag_id: datas.price_pics[i].tag_id || '', // 需
            price: datas.price_pics[i].price,
            tag_name: datas.price_pics[i].tag_name
          })
        }
        // 如果有店内照片则调用接口
        if (datas.store_pics.length) {
          this.getPictureTag(1)
        }
        // 如果有价格表图片则调用接口
        if (datas.price_pics.length) {
          this.getPictureTag(2)
        }
        paramsData = JSON.stringify(this.params)
        // console.log()
      })
    },
    // 表单校验
    // 客服电话校验
    handleSerPhone (e) {
      if (e.target.value !== '') {
        let value = isPhone(e.target.value) || Landline(e.target.value)
        if (!value) {
          this.valid1 = {
            status: 'error',
            txt: '请输入合法的客服电话'
          }
        } else {
          this.valid1 = {
            status: 'success',
            txt: ''
          }
        }
      } else {
        this.valid1 = {
          status: 'success',
          txt: ''
        }
      }
    },
    // 身份证号校验
    handleIdno (e) {
      if (e.target.value !== '') {
        let value = CheckCardNo(e.target.value)
        if (!value) {
          this.valid2 = {
            status: 'error',
            txt: '请输入合法的身份证号'
          }
        } else {
          this.valid2 = {
            status: 'success',
            txt: ''
          }
        }
      } else {
        this.valid2 = {
          status: 'success',
          txt: ''
        }
      }
    },
    // handleBankcard
    handleBankcard (e) {
      if (e.target.value !== '') {
        let value = isCardNum(e.target.value)
        if (!value) {
          this.valid3 = {
            status: 'error',
            txt: '请输入正确的银行账号'
          }
        } else {
          this.valid3 = {
            status: 'success',
            txt: ''
          }
        }
      } else {
        this.valid3 = {
          status: 'success',
          txt: ''
        }
      }
    },
    // 手机号
    handlePhone (e) {
      if (e.target.value !== '') {
        let value = isPhone(e.target.value)
        if (!value) {
          this.valid4 = {
            status: 'error',
            txt: '请输入正确的手机号'
          }
        } else {
          this.valid4 = {
            status: 'success',
            txt: ''
          }
        }
      } else {
        this.valid4 = {
          status: 'success',
          txt: ''
        }
      }
    },
    // 省市区
    selectArea({ area, provinceId, cityId, districtId }) {
      this.params.province_id = provinceId
      this.params.city_id = cityId
      this.params.district_id = districtId
      this.params.basic_area = area
    },
    // 开户地区
    selectBranchArea({ area, provinceId, cityId, districtId }) {
      this.params.bank_province_id = provinceId
      this.params.bank_city_id = cityId
      this.params.bank_district_id = districtId
      this.params.branch_area = area
    },
    // 营业时间
    changeBeginTime(time, timeStr) {
      this.params.business_start = timeStr
    },
    changeEndTime(time, timeStr) {
      this.params.business_end = timeStr
    },
    // 图片上传
    handleChange({ file }) {
      // let { originFileObj } = fileList[fileList.length - 1];
      // this.fileList = fileList;
      let formData = new FormData()
      formData.append('image', file)
      console.log(formData)
      uploadImg(formData).then(res => {
        let imgInfo = Object.assign(this.storeImgs[this.imgIndex] || {}, {
          id: '',
          name: '',
          url: res.data.url,
          tag_id: '',
          price: '',
          tag_name: ''
        })
        this.$set(this.storeImgs, this.imgIndex, imgInfo)
      })
    },
    handleProductChange({ file }) {
      let formData = new FormData()
      formData.append('image', file)
      uploadImg(formData).then(res => {
        let imgInfo = Object.assign(this.productPics[this.imgIndex] || {}, {
          id: '',
          name: '',
          url: res.data.url,
          tag_id: '',
          price: '',
          tag_name: ''
        })
        this.$set(this.productPics, this.imgIndex, imgInfo)
      })
    },
    handlePriceChange({ file }) {
      let formData = new FormData()
      formData.append('image', file)
      uploadImg(formData).then(res => {
        let imgInfo = Object.assign(this.priceImg[this.imgIndex] || {}, {
          id: '',
          name: '',
          url: res.data.url,
          tag_id: '',
          price: '',
          tag_name: ''
        })
        this.$set(this.priceImg, this.imgIndex, imgInfo)
      })
    },
    handleChangeHeadImg({ file }) {
      console.log(file)
      let formData = new FormData()
      formData.append('image', file)
      console.log(formData)
      uploadImg(formData).then(res => {
        this.loading = false
        this.params.head_img = res.data.url
      })
    },
    handleChangeLicenseImg({ file }) {
      let formData = new FormData()
      formData.append('image', file)
      uploadImg(formData).then(res => {
        this.params.license = res.data.url
      })
    },
    handleChangeLicensePermitImg({ file }) {
      let formData = new FormData()
      formData.append('image', file)
      uploadImg(formData).then(res => {
        this.params.license_premit = res.data.url
      })
    },
    // 保存时的确认框
    confirmHint(item, type) {
      if (type === 'save') {
        this.hint = 5
      }
      this.$refs.openModal.openModal()
    },
    checkImgs() {
      let isStoreImg = false
      let isProductImg = false
      let isPriceImg = false
      for (let i = 0; i < this.storeImgs.length; i++) {
        if (!this.storeImgs[i].url) {
          isStoreImg = true
        }
      }
      for (let j = 0; j < this.productPics.length; j++) {
        if (!this.productPics[j].url) {
          isProductImg = true
        }
      }
      for (let k = 0; k < this.priceImg.length; k++) {
        if (!this.priceImg[k].url) {
          isPriceImg = true
        }
      }
      if (isStoreImg) {
        this.$message.info('请先上传店内照片')
        return false
      }
      if (isProductImg) {
        this.$message.info('请先上传产品照片')
        return false
      }
      if (isPriceImg) {
        this.$message.info('请先上传价格照片')
        return false
      }
      return true
    },
    // 添加店内
    addstore() {
      if (!this.checkImgs()) {
        return false
      }
      this.storeImgs.unshift({
        id: '',
        name: '',
        url: '',
        tag_id: '',
        price: '',
        tag_name: ''
      })
      this.getPictureTag(1)
    },
    // 添加产品
    addProduct() {
      if (!this.checkImgs()) {
        return false
      }
      this.productPics.unshift({
        id: '',
        name: '',
        url: '',
        tag_id: '',
        price: '',
        tag_name: ''
      })
    },
    // 添加价格
    addPrice() {
      if (!this.checkImgs()) {
        return false
      }
      this.priceImg.unshift({
        id: '',
        name: '',
        url: '',
        tag_id: '',
        price: '',
        tag_name: ''
      })
      this.getPictureTag(2)
    },
    // 保存接口
    saveMsg() {
      sends = {
        id: this.$route.query.id,
        tag_id: this.params.tag_id, // 商家分类子id
        basic_area: this.params.basic_area,
        province_id: this.params.province_id,
        city_id: this.params.city_id,
        district_id: this.params.district_id,
        location: this.params.location,
        lon: this.params.lon,
        lat: this.params.lat,
        address_detail: this.params.address_detail,
        branch_area: this.params.branch_area,
        bank_province_id: this.params.bank_province_id,
        bank_city_id: this.params.bank_city_id,
        bank_district_id: this.params.bank_district_id,
        partner_name: this.params.partner_name, // 推荐人姓名
        partner_phone: this.params.partner_phone, // 推荐人手机号
        pa_id: this.params.pa_id, // 推荐人id
        store_name: this.params.store_name,
        per_consume: this.params.per_consume,
        service_phone: this.params.service_phone,
        amount: this.params.amount,
        discount: this.params.discount,
        law_name: this.params.law_name,
        law_idno: this.params.law_idno,
        merchant_name: this.params.merchant_name,
        bank_type: this.params.bank_type,
        bank_id: this.params.bank_id,
        bankname: this.params.bankname, // 开户银行
        bankcard: this.params.bankcard,
        branchname: this.params.branchname,
        member_account: this.params.member_account, // 会员账号
        member_id: this.params.member_id,
        phone: this.params.phone,
        business_start: this.params.business_start,
        business_end: this.params.business_end,
        head_img: this.params.head_img,
        license: this.params.license,
        license_premit: this.params.license_premit,
        store_pics: this.storeImgs,
        price_pics: this.priceImg,
        product_pics: this.productPics
      }
      sendData = JSON.stringify(sends)
    },
    // 返回详情
    backDeatil () {
      this.$router.push({
        path: '/menu/provider/InvitemerchantsDetail',
        query: { id: this.$route.query.id }
      })
    },
    // 点击确认保存
    handleConfirmOk() {
      if (!this.checkImgs()) {
        return false
      }
      this.saveMsg()
      if (sendData === paramsData) {
        console.log(sendData)
        this.$message.success('保存成功')
        this.backDeatil()
        return false
      }
      inviteUpdate(sends).then(res => {
        this.$message.success(res.data.message)
        this.backDeatil()
      })
    },
    // 点击返回弹出弹窗
    backConfirm() {
      this.saveMsg()
      if (sendData === paramsData) {
        this.backDeatil()
      } else {
        this.backVisible = true
      }
    },
    closePop () {
      this.backVisible = false
    },
    // 弹出地图弹窗
    selectAddress() {
      this.visible = true
    },
    // 删除图片(店内 价格 产品)
    deleteImg(key, index) {
      this[key].splice(index, 1)
    },
    deleteProductPic(index) {
      this.productPics.splice(index, 1)
    },
    // 地图
    infohtmlset(addr) {
      this.keyword = addr.address
      this.addrName = addr.address
      this.lat = addr.point.lat
      this.lng = addr.point.lng
    },
    handleMapOk() {
      this.visible = false
      this.params.location = this.addrName
      this.params.lat = this.lat + ''
      this.params.lon = this.lng + ''
    },
    backList() {
      this.$router.go(-1)
    },
    // 获取会员
    getMember() {
      let params = {
        page: 1,
        num: 10,
        name: this.memberName
      }
      this.menberLoading = true
      getMember(params).then(res => {
        if (!res.error) {
          this.menberLoading = false
          this.menberData = res.data.list
        }
      })
    },
    // 获取服务商
    getPartner() {
      let params = {
        page: 1,
        num: 10,
        name: this.SPName
      }
      this.SPLoading = true
      getPartner(params).then(res => {
        if (!res.error) {
          this.SPLoading = false
          this.SPData = res.data.list
        }
      })
    },
    getPictureTag(type) {
      getPictureTag({ type }).then(res => {
        if (!res.error) {
          // 店内照片
          if (type == 1) {
            this.storeTag = res.data
          } else if (type === 2) {
            // 价格照片
            this.priceTag = res.data
          }
        }
      })
    },
    // 确定会员
    ChoiceMenber() {
      this.params.member_account = temporaryData.account
      this.params.member_id = temporaryData.id
      this.menberShow = false
      this.menberDisabled = false
    },
    // 确定服务商
    ChoiceSP() {
      this.params.partner_name = temporaryData.name
      this.params.partner_phone = temporaryData.phone
      this.params.pa_id = temporaryData.id
      this.nameDisabled = false
      this.SPShow = false
    },
    // 取消（会员弹窗）
    cancelMenber() {
      this.menberShow = false
      this.menberDisabled = false
    },
    // 取消（服务商弹窗）
    cancelSP() {
      this.nameDisabled = false
      this.SPShow = false
    }
  }
}
</script>
<style lang="scss" scoped>
.search {
  float: right;
}
</style>
